#include <iostream>
#include <sstream>
#include <string>
#include <memory>
#include "Socket.hpp"
#include "Protocol.hpp"

using namespace std;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "Incorrect use: " << endl
             << "    " << argv[0] << "ip port" << endl;
        return 1;
    }

    string ip = argv[1];
    uint16_t port = stoi(argv[2]);

    unique_ptr<Socket> up(new TcpSocket());
    if (!up->BiuldTcpClient(ip, port))
    {
        up->CloseFd(true);

        cout << "连接失败" << endl;
        return -1;
    }

    while (true)
    {
        string buffer;
        cout << "请输入两个操作数，和操作符（以空格分割）：";
        getline(cin, buffer);
        send(up->GetSockFd(), (void *)buffer.c_str(), buffer.size(), 0);

        char readbuffer[128];
        recv(up->GetSockFd(), (void *)readbuffer, sizeof(readbuffer) - 1, 0);

        Response rp(readbuffer);

        cout << "结果为：" << rp.GetResult();
        if (rp.GetCode() == 0)
            cout << "，结果可信" << endl;
        else if (rp.GetCode() == -1)
            cout << "，结果不可信" << endl;
        else if (rp.GetCode() == -2)
            cout << "，操作符错误" << endl;
    }

    // while (true)
    // {
    //     int x, y;
    //     char op;
    //     cout << "请输入两个操作数，和操作符（以空格分割）：";
    //     cin >> x >> y >> op;
    //     Request rq(x, y, op);
    //     send(up->GetSockFd(), (void *)&rq, sizeof(rq), 0);
    //     Response rp;
    //     recv(up->GetSockFd(), (void *)&rp, sizeof(rp), 0);
    //     cout << "结果为：" << rp.GetResult();
    //     if (rp.GetCode() == 0)
    //         cout << "，结果可信" << endl;
    //     else if (rp.GetCode() == -1)
    //         cout << "，结果不可信" << endl;
    //     else if (rp.GetCode() == -2)
    //         cout << "，操作符错误" << endl;
    // }

    up->CloseFd(true);
    return 0;
}